define(['knockout',
    'platform.common',
    'bootbox',
    'knockout-bsTable',
    'knockout-component',
    'sco.msg',
    'knockout-fileinput',
    'websocket'], function (ko, platform) {
        // 服务交互
        var rest = {
            remove: function (tgId) {
                var param = {};
                param.tg_id = tgId;
                platform.servicebreakAsync('~/rest/tg/delete', param, 'post')
                    .done(function (response) {
                        if (response instanceof Object && response.meta.success) {
                            platform.showOperTip('DELSUC');
                            viewModel.tableViewModel.refresh();
                        } else {
                            platform.showErrorTip(response.meta.message);
                        }
                    });
            }
        };
        var kbTable = require('knockout-bsTable');
        var kbFileInput = require('knockout-fileinput');
        var bootbox = require('bootbox');
        var socket = null;
        var modelTypes = platform.servicebreak("~/rest/modelLib/getModelLibByType", {model_type: '01'}).responseJSON.responseObject;

        var ViewModel = function () {
            var self = this;
            self.columns = [{checkbox: true, align: 'center', width: 30}, {
                field: 'display_order', title: '序号',
                formatter: function (value, row, index) {
                    var options = self.tableViewModel.getOptions();
                    var indexPageNum = parseInt(options.pageNumber);
                    var indexPageSize = parseInt(options.pageSize);
                    return ((indexPageNum - 1) * indexPageSize)
                        + (index + 1);
                },
                width: 35, align: 'center'
            }, {field: 'tg_id', title: '台区标识', width: 120, visible: false}, {
                field: 'tg_no',
                title: '台区编号',
                width: 120,
                align: 'left'
            }, {field: 'tg_name', title: '台区名称', width: 180, align: 'left'}, {
                field: 'tg_capacity',
                title: '台区容量(kVA)',
                width: 120,
                align: 'right'
            }, {title: ''}];
            self.tableViewModel = new kbTable.bootstrapTableViewModel({
                url: platform.mapUrl('~/rest/tg/list'),
                toolbar: '#toolbar',
                queryParams: function (params) {
                    return {
                        pageNumber: params.offset / params.limit + 1,
                        pageSize: params.limit
                    };
                },
                columns: self.columns
            });
            self.code = ko.observable();
            self.fnImport = function () {
                bootbox.confirm({
                    title: '<h4><i class="fa fa-warning text-danger"></i>导入前提示</h4>',
                    size: 'large',
                    message: "<p>导入数据前，请认真阅读以下内容:</p>" +
                    "<p>1.请确认表格文件中设备型号（包括配变、线路分段、进户线、电能表）数据是否已在系统中维护?缺失将无法进行标杆值计算.</p>" +
                    "<p>2.原则上配电变压器后接出一条分段，若变压器接出多段分段，请自行维护一条自变压器接出的虚拟分段及虚拟杆塔，原变压器接出线段挂接在该虚拟杆塔下!</p>",
                    buttons: {
                        confirm: {
                            label: '确认',
                            className: 'btn-success btn-sm'
                        },
                        cancel: {
                            label: '取消',
                            className: 'btn-default btn-sm'
                        }
                    },
                    callback: function (response) {
                        if (response) {
                            self.importViewModel.showForm();
                            $('#importDialog').toggleClass('hide');
                        }
                    }
                });
            };
            self.fnEdit = function () {
                var selections = self.tableViewModel.getSelections();
                if (selections.length === 1) {

                } else {
                    platform.showTip('edit');

                }
            };
            self.fnView = function () {
                var selections = self.tableViewModel.getSelections();
                if (selections.length === 1) {
                    self.viewedImportVisible(true);
                    self.viewImportedModel.showForm(selections[0].tg_id, selections[0].tg_name);

                    $('#viewDlg').toggleClass('hide');
                } else {
                    platform.showTip('VIEW');
                }
            };
            self.fnRemove = function () {
                var selections = self.tableViewModel.getSelections();
                if (selections.length === 1) {
                    bootbox.confirm({
                        title: '<i class="fa fa-warning"></i>&nbsp;&nbsp;删除提示信息',
                        size: 'small',
                        message: '删除台区时，将级联删除其关联的如配变、低压线路、线路分段、低压用户等信息，确认是否删除?',
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success btn-sm'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-default btn-sm'
                            }
                        },
                        callback: function (response) {
                            if (response) {
                                var id = selections[0].tg_id;
                                rest.remove(id);
                            }
                        }
                    });
                } else {
                    platform.showTip('remove');

                }
            };
            // 导入对话框
            // self.onFileuploaded = function (event, data, previewId, index) {
            //     console.log("test outer");
            // };
            self.importModalVisible = ko.observable(false);
            self.importViewModel = {
                title: ko.observable(),
                code: ko.observable(),
                isEnabled: ko.observable(true),
                processMsg: ko.observable(),
                showForm: function () {//打开Modal
                    this.title('导入基础档案及运行数据');
                    self.importModalVisible(true);
                },
                upload: function () {//页面导入
                    var that = this;
                    that.isEnabled(false);
                    socket = new websocket();
                    this.code(socket.code);
                    socket.init({
                        onmessage: function (msg) {
                            console.log("fileInput:" + msg);
                            if (that.processMsg() == undefined || that.processMsg() == '') {
                                that.processMsg(msg);
                            } else {
                                that.processMsg(that.processMsg() + '\n' + msg);
                            }
                        }
                    });
                    $('#uploadFile').fileinput('upload');
                },
                // onFileuploaded: function (event, data, previewId, index) {
                //     console.log("test");
                // },
                close: function () {//关闭表单
                    if (socket != null) {
                        socket.close();
                    }

                    var that = this;
                    that.isEnabled(true);
                    that.processMsg('');
                    $('#uploadFile').fileinput('clear');
                    self.importModalVisible(false);
                    $('#importDialog').toggleClass('hide');
                    self.tableViewModel.refresh();
                }
            };
            self.importViewModel.parseFileModel = new kbFileInput.fileInput('~/rest/theory/parseExcel', {
                uploadExtraData: function (previewId, index) {
                    var obj = {};
                    obj.code = self.importViewModel.code();
                    return obj;
                },
                allowedFileExtensions: ['xls', 'xlsx']
            });
            self.viewedImportVisible = ko.observable(false);
            self.viewImportedModel = {
                title: ko.observable(),
                fixedTranId: ko.observable(),
                dateTable: new kbTable.bootstrapTableViewModel({
                    columns: [{checkbox: true, align: 'center', width: 30},
                        {
                            field: 'display_order', title: '序号', width: 35, align: 'center',
                            formatter: function (value, row, index) {
                                var options = self.viewImportedModel.dateTable.getOptions();
                                var indexPageNum = parseInt(options.pageNumber);
                                var indexPageSize = parseInt(options.pageSize);
                                return ((indexPageNum - 1) * indexPageSize) + (index + 1);
                            }
                        },
                        {field: 'tran_id', title: '主键标识', visible: false},
                        {field: 'section_date', title: '断面日期', width: 100, align: 'center'}],
                    showRefresh: false,
                    showColumns: false,
                    queryParams: function (params) {
                        return {
                            pageNumber: params.offset / params.limit + 1,
                            pageSize: params.limit
                            // tg_id: self.viewImportedModel.fixedTgId()
                        };
                    }
                }),
                tranTable: new kbTable.bootstrapTableViewModel({
                    columns: [{checkbox: true, align: 'center', width: 30}, {
                        field: 'display_order', title: '序号',
                        formatter: function (value, row, index) {
                            var options = self.viewImportedModel.tranTable.getOptions();
                            var indexPageNum = parseInt(options.pageNumber);
                            var indexPageSize = parseInt(options.pageSize);
                            return ((indexPageNum - 1) * indexPageSize) + (index + 1);
                        }, width: 35, align: 'center'
                    }, {field: 'tran_id', title: '配变标识', width: 120, visible: false}, {
                        field: 'tran_no', title: '配变编号', width: 120, align: 'left'
                    }, {field: 'tran_name', title: '配变名称', width: 120}, {
                        field: 'tran_model', title: '型号', width: 80,
                        align: 'center', formatter: function (value, row, index) {
                            var showText = null;
                            $.each(modelTypes, function (index, node) {
                                if (node.model_id === value) {
                                    showText = node.model_no;
                                }
                            });
                            return showText;
                        }
                    }, {field: 'section_date', title: '断面日期', width: 100, align: 'center'}, {
                        field: 'record_date', title: '记录日期', width: 120, align: 'center'}],
                    toolbar: '#tranToolbar', showRefresh: false,
                    queryParams: function (params) {
                        return {
                            pageNumber: params.offset / params.limit + 1,
                            pageSize: params.limit,
                            tran_id: self.viewImportedModel.fixedTranId()
                        };
                    }
                }),
                segTable: new kbTable.bootstrapTableViewModel({
                    toolbar: '#segToolbar', showRefresh: false,
                    columns: [
                        {checkbox: true, align: 'center', width: 30},
                        {field: 'display_order', title: '序号', width: 35, align: 'center',
                            formatter: function (value, row, index) {
                                var options = self.viewImportedModel.segTable.getOptions();
                                var indexPageNum = parseInt(options.pageNumber);
                                var indexPageSize = parseInt(options.pageSize);
                                return ((indexPageNum - 1) * indexPageSize)
                                    + (index + 1);
                            }
                        },
                        {field: 'seg_id', title: '分段标识', visible: false},
                        {field: 'seg_no', title: '分段编号' }, {field: 'start_pos', title: '起点位置标识', visible: false},
                        {field: 'start_pole_no', title: '起点位置'},
                        {field: 'start_type', title: '起点类型', formatter: function (value, row, index) {
                                if (value == '01') {
                                    return '配电变压器';
                                } else if (value == '03') {
                                    return '杆塔';
                                }
                            }
                        },
                        {field: 'end_pos',title: '终点位置标识', visible: false},
                        {field: 'end_pole_no', title: '终点位置'},
                        {field: 'end_type', title: '终点类型', formatter: function (value, row, index) {
                            if (value == '01') {
                                return '配电变压器';
                            } else if (value == '03') {
                                return '杆塔';
                            }
                        }
                    }, {
                        field: 'seg_model',
                        title: '型号',
                        visible: false
                    }, {field: 'model_no', title: '型号'}, {field: 'resistance_value', title: '单位电阻(Ω)', align: 'right'}, {
                        field: 'seg_length',
                        title: '长度(m)', align: 'right'
                    }, {field: 'line_id', title: '所属线路标识', visible: false}, {field: 'line_name', title: '所属线路'}],
                    queryParams: function (params) {
                        return {
                            pageNumber: params.offset / params.limit + 1,
                            pageSize: params.limit,
                            tran_id: self.viewImportedModel.fixedTranId()
                        };
                    }
                }),
                consLineTable: new kbTable.bootstrapTableViewModel({
                    columns: [{checkbox: true, align: 'center', width: 30}, {
                        field: 'display_order', title: '序号', width: 35, align: 'center',
                        formatter: function (value, row, index) {
                            var options = self.viewImportedModel.segTable.getOptions();
                            var indexPageNum = parseInt(options.pageNumber);
                            var indexPageSize = parseInt(options.pageSize);
                            return ((indexPageNum - 1) * indexPageSize)
                                + (index + 1);
                        }
                    }, {field: 'cl_id', title: '进户线标识', visible: false}, {field: 'cl_no', title: '编号'}, {
                        field: 'cl_model',
                        title: '型号标识',
                        visible: false
                    }, {field: 'model_no', title: '型号'}, {
                        field: 'start_pos',
                        title: '起点位置'
                    }, {field: 'cl_length', title: '长度(m)', align: 'right'}, {
                        field: 'container_id',
                        title: '关联计量箱标识',
                        visible: false
                    }, {field: 'container_no', title: '计量箱编号'}],
                    toolbar: '#consLineToolbar', showRefresh: false,
                    queryParams: function (params) {
                        return {
                            pageNumber: params.offset / params.limit + 1,
                            pageSize: params.limit,
                            tran_id: self.viewImportedModel.fixedTranId()
                        };
                    }
                }),
                consTable: new kbTable.bootstrapTableViewModel({
                    toolbar: '#consToolbar', showRefresh: false,
                    columns: [{checkbox: true, align: 'center', width: 30}, {
                        field: 'display_order', title: '序号', width: 35, align: 'center',
                        formatter: function (value, row, index) {
                            var options = self.viewImportedModel.consTable.getOptions();

                            var indexPageNum = parseInt(options.pageNumber);
                            var indexPageSize = parseInt(options.pageSize);

                            return ((indexPageNum - 1) * indexPageSize)
                                + (index + 1);
                        }
                    },
                        {field: 'asset_no', title: '表箱编号'},
                        {field: 'cons_id', title: '用户标识', visible: false},
                        {field: 'cons_no', title: '用户编号' },
                        {field: 'meter_asset_no', title: '电能表资产编号'},
                        {field: 'obj_id', title: '电量数据主键标识', visible: false },
                        {field: 'data_date', title: '电量数据日期'},
                        {field: 'data_value', title: '电量(kWh)', align: 'right'}],
                    queryParams: function (params) {
                        return {
                            pageNumber: params.offset / params.limit + 1,
                            pageSize: params.limit,
                            tran_id: self.viewImportedModel.fixedTranId()
                        };
                    }
                }),
                showForm: function (id, name) {
                    var that = this;
                    that.dateTable.load(platform.mapUrl('~/rest/tran/list'), {tg_id: id});

                    $('#dateTable').on('dbl-click-row.bs.table', function (event, row, el) {
                        that.fixedTranId(row.tran_id);

                        var param = {};
                        param.tran_id = row.tran_id;

                        that.tranTable.load(platform.mapUrl('~/rest/tran/list'), param);
                        that.segTable.load(platform.mapUrl('~/rest/seg/getSegsByParamInPage'), param);
                        that.consLineTable.load(platform.mapUrl('~/rest/cl/getConsLinesByParamInPage'), param);
                        that.consTable.load(platform.mapUrl('~/rest/record/getConsPowerByParamInPage'), param);
                    });

                    this.title('【' + name + '】台区数据查看');
                }, close: function () {
                    //关闭时清空表格内容
                    this.tranTable.removeAll();
                    this.segTable.removeAll();
                    this.consLineTable.removeAll();
                    this.consTable.removeAll();

                    self.viewedImportVisible(false);
                    $('#viewDlg').toggleClass('hide');
                }
            };
            return self;
        };
        var viewModel = new ViewModel();
        return viewModel;
    }
);